<template>
  <div class="register-page">
    <!-- 顶部黄色区域 -->
    <div class="top-section">
      <van-icon name="arrow-left" class="back-icon" @click="goBack" />
      <h1 class="register-title">用户注册</h1>
      <p class="register-subtitle">注册账号发现更多精彩</p>
      <!-- 卡通小狗 -->
      <div class="dog-illustration">
        <img
          src="../photo/小狗出售-copy.png"
          alt="cartoon dog"
          class="dog-img"
        />
      </div>
    </div>

    <!-- 表单区域 -->
    <div class="form-section">
      <!-- 头像上传 -->
      <div class="avatar-upload">
        <div class="avatar-label">头像</div>
        <div class="avatar-content">
          <div class="avatar-preview" @click="showUploadAction = true">
            <img v-if="avatarUrl" :src="avatarUrl" alt="头像" class="avatar-img" />
            <div v-else class="avatar-placeholder">
              <van-icon name="user-circle-o" size="24" />
              <span>点击上传</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户名输入 -->
      <van-field
        v-model="registerForm.username"
        label="用户名"
        placeholder="请输入用户名(2-10个字符)"
        :error-message="usernameError"
        :error="!!usernameError"
        class="custom-field"
        @input="onUsernameInput"
        @blur="validateUsername"
      >
        <template #button>
          <van-icon name="cross" @click="clearField('username')" v-if="registerForm.username" />
        </template>
      </van-field>

      <!-- 邮箱输入 -->
      <van-field
        v-model="registerForm.email"
        label="邮箱"
        placeholder="请输入邮箱地址"
        :error-message="emailError"
        :error="!!emailError"
        class="custom-field"
        @input="onEmailInput"
        @blur="validateEmail"
      >
        <template #button>
          <van-icon name="cross" @click="clearField('email')" v-if="registerForm.email" />
        </template>
      </van-field>

      <!-- 手机号输入 -->
      <van-field
        v-model="registerForm.phone"
        label="手机号"
        placeholder="请输入手机号(11位数字)"
        :error-message="phoneError"
        :error="!!phoneError"
        class="custom-field"
        @input="onPhoneInput"
        @blur="validatePhone"
      >
        <template #button>
          <van-icon name="cross" @click="clearField('phone')" v-if="registerForm.phone" />
        </template>
      </van-field>

      <!-- 密码输入 -->
      <van-field
        v-model="registerForm.password"
        type="password"
        label="密码"
        placeholder="请输入密码(5-20个字符)"
        :error-message="passwordError"
        :error="!!passwordError"
        class="custom-field"
        @input="onPasswordInput"
        @blur="validatePassword"
      />

      <!-- 确认密码输入 -->
      <van-field
        v-model="registerForm.confirmPassword"
        type="password"
        label="确认密码"
        placeholder="请再次输入密码"
        :error-message="confirmPasswordError"
        :error="!!confirmPasswordError"
        class="custom-field"
        @input="onConfirmPasswordInput"
        @blur="validateConfirmPassword"
      />

      <!-- 协议勾选框 -->
      <van-checkbox v-model="agree" class="agree-checkbox">
        我已阅读并同意《用户协议》和《隐私政策》
      </van-checkbox>

      <!-- 注册按钮 -->
      <van-button
        type="primary"
        block
        :disabled="!agree || !isFormValid"
        :loading="loading"
        @click="handleRegister"
        class="register-btn"
      >
        {{ loading ? '注册中...' : '注册' }}
      </van-button>

      <!-- 已有账号去登录 -->
      <div class="login-option">
        <van-button type="text" class="login-btn" @click="goToLogin">
          已有账号，去登录
        </van-button>
      </div>
    </div>

    <!-- 头像上传动作面板 -->
    <van-action-sheet v-model:show="showUploadAction" :actions="uploadActions" @select="onUploadSelect" />
    
    <!-- 文件上传输入框（隐藏） -->
    <input 
      type="file" 
      ref="fileInput" 
      style="display: none" 
      accept="image/*" 
      @change="handleFileChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { showSuccessToast, showFailToast } from 'vant';

const router = useRouter();

// 注册表单数据
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: '',
  avatar: null
});

const agree = ref(false);
const loading = ref(false);
const avatarUrl = ref('');
const showUploadAction = ref(false);
const fileInput = ref(null);

// 错误提示信息
const usernameError = ref('');
const passwordError = ref('');
const confirmPasswordError = ref('');
const emailError = ref('');
const phoneError = ref('');

// 上传选项
const uploadActions = [
  { name: '拍照' },
  { name: '从相册选择' }
];

// 输入事件处理
const onUsernameInput = () => {
  if (usernameError.value) {
    validateUsername();
  }
};

const onEmailInput = () => {
  if (emailError.value) {
    validateEmail();
  }
};

const onPhoneInput = () => {
  if (phoneError.value) {
    validatePhone();
  }
};

const onPasswordInput = () => {
  if (passwordError.value) {
    validatePassword();
  }
  // 密码变化时重新验证确认密码
  if (registerForm.confirmPassword && confirmPasswordError.value) {
    validateConfirmPassword();
  }
};

const onConfirmPasswordInput = () => {
  if (confirmPasswordError.value) {
    validateConfirmPassword();
  }
};

// 表单验证函数
const validateUsername = () => {
  const val = registerForm.username;
  if (!val) {
    usernameError.value = '请输入用户名';
    return false;
  }
  if (val.length < 2 || val.length > 10) {
    usernameError.value = '用户名长度为2-10个字符';
    return false;
  }
  usernameError.value = '';
  return true;
};

const validatePassword = () => {
  const val = registerForm.password;
  if (!val) {
    passwordError.value = '请输入密码';
    return false;
  }
  if (val.length < 5 || val.length > 20) {
    passwordError.value = '密码长度为5-20个字符';
    return false;
  }
  passwordError.value = '';
  return true;
};

const validateConfirmPassword = () => {
  const val = registerForm.confirmPassword;
  if (!val) {
    confirmPasswordError.value = '请再次输入密码';
    return false;
  }
  if (val !== registerForm.password) {
    confirmPasswordError.value = '两次输入的密码不一致';
    return false;
  }
  confirmPasswordError.value = '';
  return true;
};

const validateEmail = () => {
  const val = registerForm.email;
  if (!val) {
    emailError.value = '请输入邮箱';
    return false;
  }
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(val)) {
    emailError.value = '邮箱格式不正确';
    return false;
  }
  emailError.value = '';
  return true;
};

const validatePhone = () => {
  const val = registerForm.phone;
  // 手机号可选，如果为空则通过
  if (!val) {
    phoneError.value = '';
    return true;
  }
  
  // 检查是否为11位纯数字
  const phoneRegex = /^\d{11}$/;
  if (!phoneRegex.test(val)) {
    phoneError.value = '手机号必须是11位纯数字';
    return false;
  }
  
  // 检查手机号格式（1开头，第二位为3-9）
  const validPrefixRegex = /^1[3-9]\d{9}$/;
  if (!validPrefixRegex.test(val)) {
    phoneError.value = '手机号格式不正确';
    return false;
  }
  
  phoneError.value = '';
  return true;
};

// 清空字段
const clearField = (fieldName) => {
  registerForm[fieldName] = '';
  // 清空对应的错误信息
  switch (fieldName) {
    case 'username':
      usernameError.value = '';
      break;
    case 'email':
      emailError.value = '';
      break;
    case 'phone':
      phoneError.value = '';
      break;
  }
};

// 计算属性：表单是否有效
const isFormValid = computed(() => {
  return validateUsername() && 
         validatePassword() && 
         validateConfirmPassword() && 
         validateEmail() &&
         validatePhone();
});

// 头像上传处理
const onUploadSelect = (action) => {
  showUploadAction.value = false;
  
  // 触发文件选择
  if (fileInput.value) {
    fileInput.value.click();
  }
};

const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (!file) return;
  
  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    showFailToast('请选择图片文件');
    return;
  }
  
  // 检查文件大小（限制为2MB）
  if (file.size > 2 * 1024 * 1024) {
    showFailToast('图片大小不能超过2MB');
    return;
  }
  
  // 创建预览URL
  avatarUrl.value = URL.createObjectURL(file);
  registerForm.avatar = file;
  
  // 重置文件输入，允许重复选择同一文件
  event.target.value = '';
};

// 注册逻辑
const handleRegister = async () => {
  // 在提交前再次验证所有字段
  const isUsernameValid = validateUsername();
  const isPasswordValid = validatePassword();
  const isConfirmPasswordValid = validateConfirmPassword();
  const isEmailValid = validateEmail();
  const isPhoneValid = validatePhone();
  
  if (!isUsernameValid || !isPasswordValid || !isConfirmPasswordValid || !isEmailValid || !isPhoneValid) {
    showFailToast('请检查表单输入');
    return;
  }
  
  loading.value = true;
  
  try {
    // 创建FormData对象，用于文件上传
    const formData = new FormData();
    formData.append('username', registerForm.username);
    formData.append('password', registerForm.password);
    formData.append('email', registerForm.email);
    
    if (registerForm.phone) {
      formData.append('phone', registerForm.phone);
    }
    
    if (registerForm.avatar) {
      formData.append('avatar', registerForm.avatar);
    }
    
    // 这里调用注册API
    // const response = await registerApi(formData);
    
    // 模拟注册成功
    console.log('注册请求数据:', {
      username: registerForm.username,
      email: registerForm.email,
      phone: registerForm.phone,
      hasAvatar: !!registerForm.avatar
    });
    
    showSuccessToast('注册成功');
    
    // 注册成功后跳转到登录页面
    setTimeout(() => {
      router.push('/login');
    }, 1500);
    
  } catch (error) {
    console.error('注册失败:', error);
    showFailToast(error.message || '注册失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.register-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

/* 顶部黄色区域样式 */
.top-section {
  background-color: #ffd700;
  padding: 12px 20px 20px;
  position: relative;
  height: 20vh;
}

.back-icon {
  font-size: 18px;
  color: #333;
}

.register-title {
  font-size: 20px;
  font-weight: bold;
  margin: 10px 0 4px;
}

.register-subtitle {
  font-size: 13px;
  color: #666;
  margin-bottom: 10px;
}

.dog-illustration {
  position: absolute;
  bottom: -15px;
  right: 20px;
}

.dog-img {
  width: 80px;
  height: auto;
}

/* 表单区域样式 */
.form-section {
  flex: 1;
  padding: 25px 20px 20px;
  background-color: #fff;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
  margin-top: -10px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  overflow-y: auto;
}

/* 头像上传区域 */
.avatar-upload {
  display: flex;
  align-items: center;
  padding: 12px 0;
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.avatar-label {
  width: 70px;
  color: #333;
  font-size: 16px;
}

.avatar-content {
  flex: 1;
  display: flex;
  justify-content: flex-end;
}

.avatar-preview {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed #ddd;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  font-size: 12px;
}

.avatar-placeholder span {
  margin-top: 4px;
}

/* 自定义输入框样式 */
.custom-field {
  padding: 12px 0;
  margin-bottom: 0;
}

.custom-field :deep(.van-field__label) {
  width: 70px;
  color: #333;
  font-size: 16px;
}

.custom-field :deep(.van-field__body) {
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

.custom-field :deep(.van-field__control) {
  font-size: 16px;
}

/* 错误消息样式 */
.custom-field :deep(.van-field__error-message) {
  color: #ee0a24;
  font-size: 12px;
  text-align: left;
}

/* 协议勾选样式 */
.agree-checkbox {
  margin: 20px 0;
  font-size: 14px;
  color: #666;
}

.agree-checkbox :deep(.van-checkbox__icon) {
  font-size: 18px;
}

.agree-checkbox :deep(.van-checkbox__label) {
  color: #666;
}

/* 注册按钮样式 */
.register-btn {
  border-radius: 24px;
  height: 48px;
  line-height: 48px;
  font-size: 16px;
  background: linear-gradient(to right, #ffd700, #ffaa00);
  border: none;
  margin-top: 10px;
}

.register-btn:disabled {
  background: #f5f5f5;
  color: #c8c9cc;
}

/* 登录选项样式 */
.login-option {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.login-btn {
  color: #333 !important;
  font-size: 12px;
  border: none !important;
  padding: 0 !important;
  background-color: transparent !important; /* 背景透明，与页面背景融合 */
}

.login-btn :deep(.van-button__text) {
  color: #333 !important;
}
</style>